import {useEffect, useState, useRef } from "react";
import Tabbar from "components/tabBar";

import Home from './Home';
import Album from './Album';
import High from './High';
import Miniapp from './Miniapp';
import { useShareAppMessage, useShareTimeline } from '@tarojs/taro';
import {loginApi} from "./Miniapp/api";
import Modal from 'components/Modal'
import Directory from './Directory'
import Taro from "@tarojs/taro";

const pagesMap = new Map()

// pagesMap.set('high', {component: High, text: '精品', iconPath: 'rect_162', initialize: true})
pagesMap.set('album', { component: Album, text:'合集', iconPath: 'save', initialize: true })
pagesMap.set('home', { component: Home, text:'推荐', iconPath: 'home', initialize: false })
pagesMap.set('mini', {component: Miniapp, text: '我的', iconPath: 'rect_49', initialize: false})

function Index() {
  const [current, setCurrent] = useState(0)
  const paths = Array.from(pagesMap.keys())
  const lists = Array.from(pagesMap.values())
  const [show, setShow] = useState(false)
  const curAlbum = useRef({title: '', _id: ''})

  useShareAppMessage(() => {
    return {
      title: '前端码易'
    }
  })

  useShareTimeline(() => ({
    title: '前端码易'
  }))

  useEffect(() => {
    Taro.eventCenter.on('home/modal/show', (data) => {
      curAlbum.current = data
      setShow(true)
    })
    Taro.eventCenter.on('home/modal/close', () => {
      setShow(false)
    })

    const userInfo = Taro.getStorageSync('userInfo')
    if (userInfo && userInfo._id) return
    loginApi().then(res => {
      Taro.setStorageSync('userInfo', res.data);
    })
  }, []);

  return (
    <view style={window.eval as any}>
      {lists.map((item, index) => (
        <item.component
          initialize={item.initialize}
          key={item.iconPath}
          selected={current === index}
          setShow={setShow}
        />
      ))}

      <Modal show={show} onMaskClick={() => setShow(false)}>
        <Directory title={curAlbum.current.title} _id={curAlbum.current._id} />
      </Modal>

      <Tabbar
        onClick={(i) => {
          setCurrent(i);
          pagesMap.set(paths[i], {
            ...lists[i],
            initialize: true,
          });
        }}
        initial={true}
        current={current}
        backgroundColor="#ededed"
        color="#999"
        tintColor="#000"
        fixed
        tabList={lists}
      />
    </view>
  );
}

export default Index;
